﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Niunan.VideoSys.Web.Areas.Adnn1n.Controllers
{
    public class AdvertiesmentController : Controller
    {
        DAL.AdvertiesmentDAL dal = new DAL.AdvertiesmentDAL();

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 生成ad.json
        /// </summary>
        /// <returns></returns>
        public ActionResult GenAd()
        {
            try
            {
                string path = Server.MapPath("/upload/ad.json");
                FileStream fs = new FileStream(path, FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);
                //开始写入
                sw.Write(GetAdJson());
                //清空缓冲区
                sw.Flush();
                //关闭流
                sw.Close();
                fs.Close();


                return Json(new { code = 0, msg = "生成成功" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "出错：" + ex.Message });
            }
        }

        /// <summary>
        /// 读广告表生成一大坨JSON字符串
        /// </summary>
        /// <returns></returns>
        private string GetAdJson()
        {
            List<Model.AdJson_one> list_front = new List<Model.AdJson_one>();
            List<Model.AdJson_one> list_pause = new List<Model.AdJson_one>();
            List<Model.AdJson_one> list_end = new List<Model.AdJson_one>();

            List<Model.Advertiesment> list_ad = dal.GetListArray("");
            var one = list_ad.Where(a => a.remark == "front");
            foreach (var item in one)
            {
                list_front.Add(new Model.AdJson_one() { file = item.path, link = item.link, time = item.time, type = item.type });
            }

            var two = list_ad.Where(a => a.remark == "pause");
            foreach (var item in two)
            {
                list_pause.Add(new Model.AdJson_one() { file = item.path, link = item.link, time = item.time, type = item.type });
            }

            var third = list_ad.Where(a => a.remark == "end");
            foreach (var item in third)
            {
                list_end.Add(new Model.AdJson_one() { file = item.path, link = item.link, time = item.time, type = item.type });
            }

            var m = new { front = list_front, pause = list_pause, end = list_end };
            string jsonstr = Newtonsoft.Json.JsonConvert.SerializeObject(m);
            return jsonstr;
        }

        /// <summary>
        /// 拼接条件
        /// </summary>
        /// <returns></returns>
        public string GetCond(int cabh)
        {

            string cond = "1=1";

            if (cabh != 0)
            {
                switch (cabh)
                {
                    case 1:
                        cond += " and remark='front'";
                        break;
                    case 2:
                        cond += " and remark='pause'";
                        break;
                    case 3:
                        cond += " and remark='end'";
                        break;
                    default:
                        break;
                }
            }
            return cond;
        }

        /// <summary>
        /// 取总记录数
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTotalCount(int cabh)
        {
            int totalcount = dal.CalcCount(GetCond(cabh));
            return Content(totalcount.ToString());
        }

        /// <summary>
        /// 取分页数据，返回 JSON
        /// </summary>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public ActionResult List(int pageindex, int pagesize, int cabh)
        {
            List<Model.Advertiesment> list = dal.GetListArray("*", "id desc", pagesize, pageindex, GetCond(cabh));
            ArrayList arr = new ArrayList();
            foreach (var item in list)
            {
               
                arr.Add(new
                {
                    id = item.id,
                    createtime = item.createtime,
                    path = item.path,
                    type = item.type,
                    link = item.link,
                    time = item.time,
                    remark = item.remark,
                    remarkstr = item.remarkstr,
                    showimg = item.showimg,
                });
            }
            return Json(arr);
        }

        public ActionResult Add(int? id)
        {
            Model.Advertiesment n = new Model.Advertiesment();
            if (id != null)
            {
                n = dal.GetModel(id.Value);
            }
            return View(n);
        }

        [ValidateInput(false)]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Add(Model.Advertiesment m)
        {
            try
            {
                if (m.id == 0)
                {
                    dal.Add(m);
                    return Json(new { code = 0, msg = "新增成功！" });
                }
                else
                {
                    dal.Update(m);
                    return Json(new { code = 0, msg = "编辑成功！" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = $"出错：{ex.Message}" });
            }
        }

        public ActionResult Delete(string ids)
        {
            try
            {
                int success = 0;
                string[] ss = ids.Split(',');
                foreach (var item in ss)
                {
                    int x;
                    if (int.TryParse(item, out x))
                    {
                        dal.Delete(x);
                        success++;
                    }
                }
                return Json(new { code = 0, msg = "成功删除" + success + "条记录！" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = $"出错：{ex.Message}" });
            }
        }
    }
}